package com.cyf.pay.wxpay;

import com.cyf.pay.wxpay.bean.WxpayNotifyReq;
import com.cyf.pay.wxpay.bean.WxpayNotifyRsp;
import com.cyf.pay.wxpay.service.WxpayService;
import com.cyf.util.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;

/**
 * 接收微信的请求 https
 */
@RestController
@RequestMapping(value = "wxpay")
@ApiIgnore
public class WxpayHttpController {

	private static final Logger logger = LoggerFactory.getLogger(WxpayHttpController.class);

	@Autowired
	private WxpayService wxpayService;

	@PostMapping(value = "/payNotify")
	public WxpayNotifyRsp payNotify(HttpServletRequest request){
		logger.info("接收到微信异步通知===============");
		WxpayNotifyRsp rsp = new WxpayNotifyRsp();
		try {
			InputStream inputStream = request.getInputStream();
			WxpayNotifyReq req = XmlUtil.xmlToBean(inputStream, WxpayNotifyReq.class);
			return wxpayService.payNotify(req);
		} catch (Exception e) {
			rsp.setReturn_code(WxpayNotifyRsp.FAIL);
			rsp.setReturn_msg("解析参数格式失败");
			logger.error("处理APP微信支付通知异常：{}", e);
		}
		return rsp;
	}

	@PostMapping(value = "/monthlyPayNotify")
	public WxpayNotifyRsp monthlyPayNotify(HttpServletRequest request){
		logger.info("接收到微信异步通知===============");
		WxpayNotifyRsp rsp = new WxpayNotifyRsp();
		try {
			InputStream inputStream = request.getInputStream();
			WxpayNotifyReq req = XmlUtil.xmlToBean(inputStream, WxpayNotifyReq.class);
			return wxpayService.monthlyPayNotify(req);
		} catch (Exception e) {
			rsp.setReturn_code(WxpayNotifyRsp.FAIL);
			rsp.setReturn_msg("解析参数格式失败");
			logger.error("处理APP微信支付通知异常：{}", e);
		}
		return rsp;
	}
	
}
